import { makeAutoObservable } from 'mobx';
import { inject, injectable } from 'inversify';
import { AuthRepository } from '../data/auth.repository.ts';
import { APIClient, responseWithError, WithError } from '@todo/core';
import { responseLoginDTO } from '../data/auth.dto.ts';
import { CookieRepository } from '../data/cookie.repository.ts';
import { UserModel } from '../../user/models/user.model.ts';

@injectable()
export class LoginUseCase {
  constructor(
    @inject(AuthRepository)
    private authRepository: AuthRepository,
    @inject(CookieRepository)
    private cookieRepository: CookieRepository,
    @inject(UserModel)
    private userModel: UserModel,
    @inject(APIClient)
    private apiClient: APIClient,
  ) {
    makeAutoObservable(this);
  }

  async execute(
    login: string,
    password: string,
    remember: boolean,
  ): Promise<WithError<responseLoginDTO>> {
    const result = await responseWithError<responseLoginDTO>(
      this.authRepository.login(login, password),
    );

    if (result.data) {
      this.apiClient.setAuthTokens(
        result.data.data.accessToken,
        result.data.data.refreshToken,
        result.data.data.expiresIn,
        remember,
      );

      this.userModel.authenticated = true;
    }

    if (result.err) {
      this.cookieRepository.delete('token');
      this.cookieRepository.delete('refreshToken');
    }

    return result;
  }
}
